package tr.edu.metu.is.mega.client.course.activity;

import gwtupload.client.IUploader;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.SingleUploader;
import tr.edu.metu.is.mega.client.core.EditDialog;
import tr.edu.metu.is.mega.client.resource.MegaConstants;
import tr.edu.metu.is.mega.client.widgets.MegaTextField;
import tr.edu.metu.is.mega.common.dto.BaseDTO;
import tr.edu.metu.is.mega.common.dto.SubmissionDTO;

import com.extjs.gxt.ui.client.widget.form.AdapterField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FormData;

/**
 * 
 */
public class SubmissionUploadDialog extends EditDialog<SubmissionDTO> {

    private SubmissionDTO dto;

    private MegaTextField filePathField;

    /**
     * Default constructor.
     * 
     * @param className
     */
    public SubmissionUploadDialog(SubmissionDTO dto) {
        super(SubmissionDTO.class.getName(), dto);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void beforeInitForm(BaseDTO baseDTO) {
        dto = (SubmissionDTO) baseDTO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initForm(FormPanel parent, Object... params) {
        setSize(400, 200);

        filePathField = new MegaTextField("");
        filePathField.setFieldLabel("File Name");
        filePathField.setEnabled(false);
        parent.add(filePathField, new FormData("100%"));

        SingleUploader uploader = new SingleUploader();
        String prefix;
        setHeading("Upload submission file");
        prefix = MegaConstants.TEAM_PATH + dto.getTeam().getPkid() + "/submission/";
        uploader.setFileInputPrefix(prefix);
        uploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {

            @Override
            public void onFinish(IUploader uploader) {
                filePathField.setValue(uploader.getServerInfo().message);
            }
        });
        AdapterField field = new AdapterField(uploader);
        field.setFieldLabel("File");
        parent.add(field, new FormData("90%"));

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected SubmissionDTO guiToDTO() {
        dto.setFilepath(filePathField.getValue());
        return dto;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void dtoToGUI(SubmissionDTO dto) {
        this.dto = dto;
    }

}
